Custom function for inserting values into MySQL

Custom function for inserting values into MySQL

am 03.11.2009 02:32:13 von Allen McCabe

--00504502cc01ad188704776d7609
Content-Type: text/plain; charset=ISO-8859-1

Okay friends, I have been wondering about writing a simple function that
will help me with my MySQL inserting. Not because I need to save time and
space, but because I wanted to.

I wrote a function for inserting 10 values (I have not been able to come up
with an idea how to make the number of values I'm inserting variable, so I'm
sticking with ten).

This function takes 22 parameters: #1 is the table name, #2-21 are the row
names and the values, and #22 is the "integar string".

The first 21 parameters are self-explanatory, the 22nd is a string of values
that need to be inserted as an integar, basically, not adding single quotes
around the value. Eg. $value2 = 5, not $value2 = '5'.

I am very hesitant to try this one out on my database, I've got tables of
important information and don't want to, I don't know, inadvertantly throw a
wrench into the works, AND I want to open up a dialoug about custom PHP
functions for working with MySQL, for the fun of it!

Here is my 10 value function for inserting data into a MySQL database table.

function insertinto10($table, $field1, $value1, $field2, $value2, $field3,
$value3, $field4, $value4, $field5, $value5, $field6, $value6, $field7,
$value7, $field8, $value8, $field9, $value9, $field10, $value10, $int =
NULL)
{
if (isset($int))
{
$sPattern = '/\s*/m';
$sReplace = '';
$int = preg_replace($sPattern, $sReplace, $int);
$pieces = explode(",", $int); // $pieces[0], $pieces[1] - each equal to
value numbers that are integars
$length = count($pieces);
// call custom function to create associative array eg. $newarray[2] = 1,
$newarray[4] = 1, $newarray[5] = 1 . . .
$integarArray = strtoarray($length, $int);
}

$valuesArray = array($value1, $value2, $value3, $value4, $value5, $value6,
$value7, $value8, $value9, $value10);

foreach ($valuesArray as $key => $value)
{
if (isset($integarArray[$key]) && $integarArray[$key] == 1)
{
// INTEGAR VALUE
$valuesArray[$key] = mysql_real_escape_string(stripslashes($value));
}
else
{
// STRING VALUE
$cleanValue = mysql_real_escape_string(stripslashes($value));
$valuesArray[$key] = "'{$cleanValue}'";
}
}

$result = mysql_query("INSERT INTO `{$table}` (`{$field1}`, `{$field2}`,
`{$field3}`, `{$field4}`) VALUES ({$valuesArray[1]}, {$valuesArray[2]},
{$valuesArray[3]}, {$valuesArray[4]}, {$valuesArray[5]}, {$valuesArray[6]},
{$valuesArray[7]}, {$valuesArray[8]}, {$valuesArray[9]},
{$valuesArray[10]})");
return $result;
}


You may find copying/pasting into your favorite code-editor helps make it
more readable.

Do you see any major hangups or screwups on first glance? And is my fear of
trying this out on my database unfounded? Does this even seem that useful?

--00504502cc01ad188704776d7609--

RE: Custom function for inserting values into MySQL

am 03.11.2009 02:55:50 von Daevid Vincent

------=_NextPart_000_0125_01CA5BE5.B81AC140
Content-Type: text/plain;
charset="us-ascii"
Content-Transfer-Encoding: 7bit

> Do you see any major hangups or screwups on first glance?

Yes.

There is so much wrong with this I don't even know where to begin...

> This function takes 22 parameters: #1 is the table name,
> #2-21 are the row
> names and the values, and #22 is the "integar string".

Dude. Seriously? TWENTY TWO parameters.

Use this for variable number of parameters:
http://us2.php.net/manual/en/function.func-get-args.php

Or how about using an array/hash as your second parameter with the
field=>value pairs.

Which is astonishing since you have the concept of an array with this hack:

$valuesArray = array($value1, $value2, $value3, $value4, $value5,
$value6, $value7, $value8, $value9,
$value10);
foreach ($valuesArray as $key => $value)

The word you're looking for is "INTEGER" not "INTEGAR".

> And is my fear of trying this out on my database unfounded?

No. Don't use it.

> Does this even seem that useful?

No.

Your function is so very limited in scope and use. You're better off writing
a wrapper around the SQL functions and submit direct SQL as the string
parameter to the function. See attached db.inc.php.

You would also be better served using a method/function such as my
base.class.php::sync() which will insert or update a row.

The attached code is about a year old or so and has since been refined
further, but this should give you a good place to start.

http://daevid.com

------=_NextPart_000_0125_01CA5BE5.B81AC140
Content-Type: text/plain;
name="base.class.php"
Content-Transfer-Encoding: quoted-printable
Content-Disposition: attachment;
filename="base.class.php"

#----------------------------------------------------------- --------=0A=
#=0A=
# Confidential - Property of Lockdown Networks, Inc.=0A=
# Do not copy or distribute.=0A=
# Copyright 2002-2008 Lockdown Networks, Inc. All rights reserved.=0A=
#=0A=
#----------------------------------------------------------- --------=0A=
=0A=
require_once('global.inc.php');=0A=
require_once('error.class.php');=0A=
=0A=
class baseClass=0A=
{=0A=
protected $db =3D 'V2_Data';=0A=
protected $table =3D NULL;=0A=
=0A=
protected $id =3D NULL;=0A=
protected $created_on =3D NULL;=0A=
protected $_stamp =3D NULL;=0A=
protected $enabled =3D TRUE;=0A=
=0A=
//we use generic __call __get and __set, but this is a special case.=0A=
function get_stamp() { return $this->_stamp; }=0A=
function set_stamp($stamp) { $this->_stamp =3D $stamp; }=0A=
=0A=
/**=0A=
* Constructor=0A=
* =0A=
* @access public=0A=
* @return object=0A=
* @param mixed $id the ID of the object to load from the database (this =
could be a string or usually an integer)=0A=
* @author Daevid Vincent [daevid@]=0A=
* @version 1.2=0A=
* @date 09/20/07=0A=
*/=0A=
function __construct($id =3D NULL)=0A=
{=0A=
if ($_SESSION['companydb']) $this->db =3D $_SESSION['companydb'];=0A=
=0A=
//this follows the Ruby way for ease of porting/sharring, please stick =
with the convention.=0A=
if (is_null($this->table) && preg_match( '/y$/', $this->getClassname() =
) > 0)=0A=
$this->table =3D strtolower(preg_replace( '/y$/', 'ies', =
$this->getClassName() ));=0A=
elseif( is_null( $this->table ) )=0A=
$this->table =3D strtolower($this->getClassName()).'s';=0A=
=0A=
if (!is_null($id)) $this->load($id);=0A=
}=0A=
=0A=
/**=0A=
* generate a key/value pair from the class' variables.=0A=
*=0A=
* @access public=0A=
* @return array=0A=
* @author Daevid Vincent [daevid@]=0A=
* @version 1.0=0A=
* @date 08/13/07=0A=
*/=0A=
public function get_array()=0A=
{=0A=
$row =3D array();=0A=
foreach($this as $key =3D> $value) =0A=
$row[$key] =3D $value;=0A=
=0A=
$row['enabled'] =3D ($this->enabled) ? 1 : 0;=0A=
=0A=
return $row;=0A=
}=0A=
=0A=
/**=0A=
* set the class' values based upon a SQL query.=0A=
*=0A=
* Note: Usually this is called by an extension class, =0A=
* which in turn calls the parent::load_from_sql() =0A=
* which generates an array and then calls load_from_array()=0A=
*=0A=
* @access public=0A=
* @return array or false=0A=
* @param int $id ID of the object to load=0A=
* @author Daevid Vincent [daevid@]=0A=
* @version 1.0=0A=
* @date 08/20/07=0A=
* @see load_from_array()=0A=
*/=0A=
function load($id =3D null)=0A=
{=0A=
if (intval($id) < 1) return false;=0A=
=0A=
$sql =3D "SELECT *=0A=
FROM ".$this->db.".".$this->table." =0A=
WHERE id =3D '".SQL_ESCAPE($id)."'";=0A=
=0A=
$result =3D $this->load_from_sql($sql); //LIMIT 1 is appended by base =
class=0A=
if ($result)=0A=
return $result;=0A=
else=0A=
throw new Exception(translate('%1$s threw an exception trying to load =
object #%2$s', __CLASS__, $id));=0A=
}=0A=
=0A=
/**=0A=
* set the class' values based upon a SQL table which is converted to an =
array of column(key) value pairs and passed to load_from_array().=0A=
*=0A=
* @access public=0A=
* @return array or false=0A=
* @param string $sql SQL schema columns to use as array keys=0A=
* @author Daevid Vincent [daevid@]=0A=
* @version 1.0=0A=
* @date 08/13/07=0A=
* @see load_from_array()=0A=
*/=0A=
public function load_from_sql($sql =3D null)=0A=
{=0A=
if (is_null($sql)) return false;=0A=
=0A=
$result =3D SQL_QUERY($sql." LIMIT 1");=0A=
if($result && $row =3D SQL_ASSOC_ARRAY($result))=0A=
{=0A=
return $this->load_from_array($row);=0A=
}=0A=
else return false;=0A=
}=0A=
=0A=
/**=0A=
* set the class' values based upon an array.=0A=
*=0A=
* @access public=0A=
* @return boolean=0A=
* @param array $row class or SQL schema column/value pairs=0A=
* @param array $force force loading of value pairs=0A=
* @author Daevid Vincent [daevid@]=0A=
* @version 1.1=0A=
* @date 12/17/07=0A=
* @see load_from_sql()=0A=
*/=0A=
public function load_from_array($row, $force =3D false)=0A=
{=0A=
if (!$force && intval($row['id']) < 1) return false;=0A=
=0A=
foreach($row as $key =3D> $value)=0A=
$this->$key =3D $value;=0A=
=0A=
$this->enabled =3D ($row['enabled'] == '1') ? true : false;=0A=
//$this->iterateVisible();=0A=
return true;=0A=
}=0A=
=0A=
/**=0A=
* INSERT or UPDATE an object's Database row.=0A=
*=0A=
* Pass in an array of column name/value pairs to INSERT/UPDATE those =
specifically, using schema defaults for the rest.=0A=
* =0A=
* @access public=0A=
* @return boolean false on error, true on UPDATE, record ID on INSERT=0A=
* @param array $row SQL schema column/value pairs=0A=
* @param boolean $auto_escape (true) will wrap all values in =
SQL_ESCAPE()=0A=
* @param boolean $show_errors toggle SQL errors, use SQL_ERROR_NUM() or =
SQL_ERROR() to handle yourself.=0A=
* @author Daevid Vincent [daevid@]=0A=
* @version 1.2=0A=
* @date 10/11/07=0A=
*/=0A=
public function sync($row =3D null, $auto_escape =3D true, $show_errors =
=3D true)=0A=
{=0A=
if (is_null($this->table)) return false;=0A=
=0A=
if (is_null($row)) $row =3D $this->get_array();=0A=
=0A=
if (count($row) < 1) return;=0A=
=0A=
//[dv] this is a handy way to shortcut and update a record with the =
passed in array key/vals.=0A=
if ($row['id'] < 1) unset($row['id']);=0A=
if (!$this->id && $row['id'] > 0) $this->id =3D $row['id'];=0A=
=0A=
//[dv] I thought about scrubbing the $row array of empty values, =0A=
// but that causes a problem if you actually DO want to wipe out =
some values.=0A=
=0A=
$row['enabled'] =3D ($row['enabled']) ? 1 : 0;=0A=
=0A=
if (intval($this->id) < 1) =0A=
{=0A=
$cols =3D "`".implode("`, `", array_keys($row))."`";=0A=
$temp =3D array();=0A=
foreach ( $row as $val )=0A=
{=0A=
if (!is_null($val)) =0A=
{=0A=
$value =3D trim($val);=0A=
$temp[] =3D ($auto_escape ===3D true) ? "'".SQL_ESCAPE( $val =
)."'" : $val;=0A=
}=0A=
else=0A=
$temp[] =3D "NULL";=0A=
}=0A=
$values =3D implode(', ',$temp);=0A=
$sql =3D "INSERT INTO ".$this->table." (created_on, ".$cols.") VALUES =
(NOW(), ".$values.")"; =0A=
}=0A=
else=0A=
{=0A=
$sql =3D "UPDATE ".$this->table." SET ";=0A=
unset($row['id']);=0A=
$temp =3D array();=0A=
foreach ($row as $col =3D> $value)=0A=
{=0A=
if (!is_null($value)) =0A=
{=0A=
$value =3D trim($value);=0A=
$temp[] =3D $col." =3D ".(($auto_escape ===3D true) ? =
"'".SQL_ESCAPE( $value )."'" : $value);=0A=
}=0A=
else=0A=
$temp[] =3D $col." =3D NULL";=0A=
}=0A=
$sql .=3D implode(', ', $temp);=0A=
$sql .=3D " WHERE id =3D '".$this->id."' LIMIT 1";=0A=
}=0A=
=0A=
if ($sth =3D SQL_QUERY($sql, false, $show_errors)) =0A=
{=0A=
if (intval($this->id) < 1) =0A=
{=0A=
$this->id =3D SQL_INSERT_ID();=0A=
$row['id'] =3D $this->id; //or load_from_array will fail=0A=
$this->load_from_array($row); //[dv] TODO: not sure if this is needed=0A=
AddUserLog('Action', MakeUserLog('Added %1$s =
[%2$s]',str_replace('_', ' ', $this->getClassName()), $this->id));=0A=
return $this->id;=0A=
}=0A=
else=0A=
{=0A=
$row['id'] =3D $this->id; //or load_from_array will fail=0A=
$this->load_from_array($row); //[dv] TODO: not sure if this is needed=0A=
AddUserLog('Action', MakeUserLog('Saved %1$s =
[%2$s]',str_replace('_', ' ', $this->getClassName()), $this->id));=0A=
return true;=0A=
}=0A=
}=0A=
else =0A=
return false;=0A=
}=0A=
=0A=
/**=0A=
* Delete the corresponding class object ID from the database.=0A=
*=0A=
* Note: 'delete' is a reserved word in PHP=0A=
*=0A=
* @access public=0A=
* @return boolean=0A=
* @author Daevid Vincent [daevid@]=0A=
* @version 1.1=0A=
* @date 10/10/07=0A=
*/=0A=
public function delete()=0A=
{=0A=
if( intval( $this->id ) < 1 )=0A=
return( false );=0A=
=0A=
if (SQL_QUERY("DELETE FROM ".$this->db.".".$this->table." WHERE id =3D =
'".$this->id."' LIMIT 1")) =0A=
{=0A=
AddUserLog('Action', MakeUserLog('Deleted %1$s =
[%2$s]',str_replace('_', ' ', $this->getClassName()), $this->id));=0A=
=0A=
foreach($this as $key =3D> $value) =0A=
$this->$key =3D null;=0A=
=0A=
return true;=0A=
}=0A=
else =0A=
return false;=0A=
}=0A=
=0A=
/**=0A=
* Shows all exposed variables in this class=0A=
*=0A=
* @access public=0A=
* @return array=0A=
* @param boolean $print to print out each value=0A=
* @author Daevid Vincent [daevid@]=0A=
* @version 1.0=0A=
* @date 08/13/07=0A=
*/=0A=
public function iterateVisible($print =3D false) =0A=
{=0A=
if ($print) echo =
"\n
".$this->getClassName()."::iterateVisible:
\n";=0A=
=0A=
$tmp =3D array();=0A=
foreach($this as $key =3D> $value) =0A=
{=0A=
$tmp[$key] =3D $value;=0A=
if ($print) print $key." =3D> ".$value."
\n";=0A=
}=0A=
=0A=
return $tmp;=0A=
}=0A=
=0A=
/**=0A=
* returns the name of this class as a string=0A=
* =0A=
* @access public=0A=
* @return string=0A=
* @author Daevid Vincent [daevid@]=0A=
* @version 1.0=0A=
*/=0A=
public function getClassName()=0A=
{=0A=
//return __CLASS__;=0A=
return get_class($this);=0A=
}=0A=
=0A=
/**=0A=
* Provides generic getters and setters=0A=
*=0A=
* @access public=0A=
* @param string $method The method name.=0A=
* @param array $arguments The arguments passed to the method.=0A=
* @return mixed=0A=
* @author Daevid Vincent [daevid@]=0A=
* @date 08/21/2007=0A=
* @version 1.1=0A=
* @see __get(), __set()=0A=
*/=0A=
public function __call( $method, $arguments )=0A=
{=0A=
$prefix =3D strtolower( substr( $method, 0, 3 ) );=0A=
$property =3D strtolower( substr( $method, 4 ) );=0A=
=0A=
if ( empty($prefix) || empty($property) ) return;=0A=
=0A=
if ( 'get' == $prefix )=0A=
{ =0A=
if ( property_exists($this, $property) )=0A=
return $this->$property;=0A=
else=0A=
return $this->__get($property);=0A=
}=0A=
elseif ( 'set' == $prefix )=0A=
{=0A=
if ( property_exists($this, $property) )=0A=
return $this->$property =3D $arguments[0];=0A=
else=0A=
return $this->__set($property, $arguments[0]);=0A=
}=0A=
=0A=
echo "

Attempted to '".$method."' =
variable in class '".$this->getClassName()."'.

\n";=0A=
backtrace();=0A=
}=0A=
=0A=
/**=0A=
* magic function to handle any accessing of undefined variables.=0A=
* Since PHP is "lax" this will help prevent stupid mistakes.=0A=
* =0A=
* @access public=0A=
* @return void=0A=
* @param mixed $var name of the variable=0A=
* @author Daevid Vincent [daevid@]=0A=
* @version 1.0=0A=
* @date 08/13/07=0A=
* @see __set(), __call()=0A=
*/=0A=
public function __get($var) =0A=
{=0A=
echo "

Attempted to __get() variable =
'".$var."' in class '".$this->getClassName()."'.

\n";=0A=
backtrace();=0A=
}=0A=
=0A=
/**=0A=
* magic function to handle any setting of undefined variables.=0A=
* Since PHP is "lax" this will help prevent stupid mistakes.=0A=
* =0A=
* @access public=0A=
* @return void=0A=
* @param mixed $var name of the variable=0A=
* @param mixed $val value of the variable=0A=
* @author Daevid Vincent [daevid@]=0A=
* @version 1.0=0A=
* @date 08/13/07=0A=
* @see __get(), __call()=0A=
*/=0A=
public function __set($var, $val) =0A=
{=0A=
echo "

Attempted to __set() variable =
'".$var."' to '".$val."' in class =
'".$this->getClassName()."'.

\n";=0A=
backtrace();=0A=
}=0A=
=0A=
/**=0A=
* The destructor method will be called as soon as all references to a =
particular object are removed =0A=
* or when the object is explicitly destroyed.=0A=
*=0A=
* This End User method will save the $_SESSION first=0A=
* http://www.php.net/session-set-save-handler=0A=
*=0A=
* @access public=0A=
* @author Daevid Vincent [daevid@]=0A=
* @since 1.0=0A=
* @version 1.0=0A=
* @date 08/13/07=0A=
*/=0A=
/*=0A=
function __destruct() =0A=
{=0A=
session_write_close();=0A=
=0A=
parent::__destruct();=0A=
}=0A=
*/=0A=
}=0A=
?>=0A=

------=_NextPart_000_0125_01CA5BE5.B81AC140
Content-Type: text/plain;
name="db.inc.php"
Content-Transfer-Encoding: quoted-printable
Content-Disposition: attachment;
filename="db.inc.php"

#----------------------------------------------------------- --------
#
# Confidential - Property of Lockdown Networks, Inc.
# Do not copy or distribute.
# Copyright 2002-2008 Lockdown Networks, Inc. All rights reserved.
#
#----------------------------------------------------------- --------

// I use this 'db.inc.php' for other modules, so that's why the =
host/user/pw are not in the globals.php file
// also, it's silly to use define() here since this is the only spot =
they're ever used.

$GLOBALS['__DB_HANDLE'] =3D false;

require_once('ironbars.php'); //[dv] why is this here? what uses it?

//TODO: [dv] we REALLY should make these all $SQLOPTION[] and update =
them in ALL files to avoid confusion and collisions...
$OPTION['host'] =3D '';
$OPTION['username'] =3D 'root';
$OPTION['password'] =3D '';
$OPTION['noHTML'] =3D false;
$OPTION['fullQuery'] =3D false;
$OPTION['useLogger'] =3D true;
$OPTION['profile'] =3D 0;
//$OPTION['outfile'] =3D false; //set this to a filename, and use =
$showSQL in your queries and they'll go to this file.

define ('MAX_SQL_ERRORS', 10);

if (!array_key_exists('autoConnect',$OPTION)) $OPTION['autoConnect'] =3D =
true;
if ($OPTION['autoConnect']) SQL_CONNECT("localhost");

/*
* We are (currently) trying to prevent just one trivial type of sql =
injection.
* Namely, the one that attempts to end query with a ; and then add an =
extra query=20
* to the end. This is a common technique, and the one that is easiest =
to detect.
*
* First, we watch for unbalanced quotes. If any are found, the query is =
invalid anyway
* and thus will not be allowed to run.
*
* Second, I can't think of a single valid use of a semicolon outside =
the literals=20
* enclosed into ''. Semicolons will be alloedd in those literals, but =
not outside.
*
* Single quotes that are in the literals and have been SQL_ESCAPE()'d =
are treated properly,
* that is as a single character within the literal. So are the =
backslashed-escaped chars.
*
* Any other additions are welcome, but this is at least a good start.
*
* @author Vlad Krupin [vlad@]
*/
function IS_SAFE_SQL_QUERY($q){
$len =3D strlen($q);
$inside =3D false; // inside a literal (enclosed by '')
$ret =3D true; // query assumed good unless we can prove otherwise.
for($i =3D 0; $i < $len; $i++)
{
$more =3D ($i < ($len - 1)); // we have at least one more character
=09
// CR3940 - we can't use the $q[$i] here because the bracket operator =
doesn't
// currently work with multibyte strings. Yuck.
switch( substr( $q, $i, 1 ) )=20
{
case "\\":
//[krogebry] Why would there be a test for '$inside' here?
// anything after a \ should be an escaped char, that's what \ =
does.
#if($inside && $more)
#{
$i++; // whatever follows MUST be an escaped character.
#continue;
#}
break;
=09
case "'":
// we are inside the string and came up with a properly-escaped quote
#if($inside && $more && ($q[$i+1] == "'")){
if($inside && $more && substr( $q, $i, $i - 1 ) == "\\" ){
$i++;
continue;
}
$inside =3D !$inside;
break;
=09
case ";":
// semicolons outside literals are not permitted.
if(!$inside) return "Possible chain query via semi-colon injection";
=09
//case "-":
// //testing for -- comments
// if (substr( $q, $i, 2 ) == '--') return "Possible '-- comment' =
injection.";
// break;
=09
}// switch()
}
if($inside) $ret =3D "Unbalanced single quotes";
=09
#print "Ret: [$ret]
\n";
return $ret;
}

/**
* Make a connection to a mysql db.
* @access public
* @author Daevid Vincent [daevid@]
*/
function SQL_CONNECT($server =3D 'localhost')
{
global $OPTION;
=09
$GLOBALS['__CONNECTED_SERVER'] =3D $server;
if (!$OPTION['username']) $OPTION['username'] =3D 'root';
if (!$OPTION['password']) $OPTION['password'] =3D '';
=09
$tries =3D 5;
for($i =3D 1; $i <=3D $tries; $i++)=20
{
switch ( strtolower($server) )
{
case "1":
case "localhost":
default:
$GLOBALS['__DB_HANDLE'] =3D @mysql_pconnect("localhost", =
$OPTION['username'], $OPTION['password']);
if (is_resource($GLOBALS['__DB_HANDLE'])) break 2;
}
=09
echo translate("Unable to connect to database. Retrying [%1\$s/%2\$s] =
in 5 seconds.\n", $i, $tries);
sleep(5);
}
=09
if (!is_resource($GLOBALS['__DB_HANDLE']))=20
{
echo translate("Could not connect to %1\$s server. Aborting.\n", =
$GLOBALS['__CONNECTED_SERVER']);
return false;
}
=09
// Set our connection, results, and client charsets to UTF-8
SQL_QUERY('SET NAMES utf8');
=09
//echo translate("Got __DB_HANDLE %1\$s", $GLOBALS['__DB_HANDLE']);
return $GLOBALS['__DB_HANDLE'];
}

/**
* Save the SQL connection object to a global area
* @access public
* @author Evan Webb [evan@]
*/
function SQL_SAVE_CONN() {
if(!isset($GLOBALS['__DB_HANDLES'])) {
$GLOBALS['__DB_HANDLES'] =3D array();
}

array_push($GLOBALS['__DB_HANDLES'],$GLOBALS['__DB_HANDLE']) ;
}

/**
* Reuse a stored connection
* @access public
* @author Evan Webb [evan@]
*/
function SQL_RESTORE_CONN($con=3Dnull) {
if(is_null($con)) {
$GLOBALS['__DB_HANDLE'] =3D array_pop($GLOBALS['__DB_HANDLES']);
} else {
$GLOBALS['__DB_HANDLE'] =3D $con;
}
}

/**
* Select a db
* @access public
* @author Daevid Vincent [daevid@]
*/
function SQL_DB($dbname, $exit =3D true)
{
if ( @mysql_select_db($dbname,$GLOBALS['__DB_HANDLE']) )
{
$GLOBALS['__CURRENT_DB'] =3D $dbname;
return true;
}
else=20
{
if ($exit == true)
exit("Could not connect to the '".$dbname."' Database.");
else
return false; //this is in case you want to do your own error =
handling.
}
}

/**
* Outputs the SQL to /tmp/SQL_profile.txt in detail.=20
*=20
* profile SQL statements in varying detail levels.
* Detail Levels:
* 1 =3D Y-m-d/ h:i:s
* 2 =3D SQL timing
* 3 =3D filename
*
* @access public
* @return boolean on success or failure.
* @param string $sql The SQL query to be executed, this can be SELECT, =
INSERT, UPDATE or DELETE amongst others.
* @param int $detail the detail level as an integer 1-3.
* @author Daevid Vincent [daevid@]
* @since 3.11
* @version 1.1
* @date 05/11/05
*/
function SQL_PROFILE($sql, $detail =3D 3 )
{
if ($detail == 0) return false;
if (!isset($sql)) return false;
=09
if (!$handle =3D fopen("/tmp/SQL_profile.txt", 'a'))=20
{
echo "unable to open file /tmp/SQL_profile.txt\n";
return false;
}

//not really required, as they're handled inherently
//if ($detail > 4) $detail =3D 4;
//if ($detail < 1) $detail =3D 1;

$text =3D date("[Y-m-d h:i:s ");

if ($detail >=3D 2) //start timer
{
list($usec, $sec) =3D explode(" ",microtime());=20
$sql_start =3D ((float)$usec + (float)$sec);
}

$result =3D @mysql_query($sql, $GLOBALS['__DB_HANDLE']);

if ($detail >=3D 2) //end timer
{
list($usec, $sec) =3D explode(" ",microtime());=20
$text .=3D number_format( (((float)$usec + (float)$sec) - $sql_start), =
4 ).'s';
}

//we do this here so as not to upset the timer too much
if ($detail >=3D 3)
{
$text .=3D ' '.$_SERVER['SCRIPT_FILENAME'];
$traceArray =3D debug_backtrace();
$text .=3D ' '.$traceArray[1]['file'].' ('.$traceArray[1]['line'].')';
$text =3D str_replace('/lockdown/', '', $text);
}

$sql =3D str_replace("\n", ' ', $sql);
$sql =3D preg_replace('/\s+/',' ', $sql);
if (!fwrite($handle, $text.'] '.$sql."\n"))=20
{
echo "unable to write to file /tmp/SQL_profile.txt\n";
return false;
}

@fclose($handle);

return $result;
} //SQL_PROFILE


/**
* Output the HTML debugging string in color coded glory for a sql query
* This is very nice for being able to see many SQL queries
* @access public
* @return void. prints HTML color coded string of the input $query.
* @param string $query The SQL query to be executed.
* @author Daevid Vincent [daevid@]
* @since 4.0
* @version 1.0
* @date 04/05/05
* @todo highlight SQL functions.
*/
function SQL_DEBUG( $query )
{
if( $query == '' ) return 0;

global $SQL_INT;
if( !isset($SQL_INT) ) $SQL_INT =3D 0;

//[dv] I like my version better...
//require_once('classes/geshi/geshi.php');
//$geshi =3D new GeSHi($query, 'sql');
//echo $geshi->parse_code();
//return;

//TODO: [dv] I wonder if a better way to do this is to split the string =
into array chunks and examine them each individually?
=09
//TODO: [dv] I think we'd get better results if we normalize the $query =
string by stripping out any \n\r characters:
$query =3D str_replace( array("\n", "\r", ' '), ' ', $query);
=09
//[dv] this has to come first or you will have goofy results later.
//[dv] UGH this number one is causing me lots of grief... why can't i =
figure out the regex to use?
//highlight numbers=20
//$query =3D preg_replace("/[\s=3D](\d+)\s/", " COLOR=3D'#FF6600'>$1", $query, -1);
//highlight strings between quote marks
$query =3D preg_replace("/(['\"])([^'\"]*)(['\"])/i", "$1 COLOR=3D'#FF6600'>$2$3", $query, -1);
//highlight functions
$query =3D preg_replace("/(\w+)\s?\(/", " COLOR=3D'#CC00FF'>".strtoupper('\\1')."(", $query, -1);
//underline tables/databases
$query =3D preg_replace("/(\w+)\./", "$1.", $query, -1);

$query =3D str_ireplace(
array (
'*',
'SELECT ',
'UPDATE ',
'DELETE ',
'INSERT ',
'INTO ',
'VALUES ',
'FROM ',
'LEFT ',
'JOIN ',
'WHERE ',
'LIMIT ',
'ORDER BY ',
'AND ',
'OR ', //[dv] note the space. otherwise you match to 'colOR' =
;-)
' DESC',
' ASC',
' ON ',
' AS '
),
array (
"*",
"SELECT ",
"UPDATE ",
"DELETE ",
"INSERT ",
"INTO ",
"VALUES ",
"FROM ",
"LEFT ",
"JOIN ",
"WHERE ",
"LIMIT ",
"ORDER BY ",
"AND ",
"OR ",
" DESC",
" ASC",
" ON ",
" AS "
),
$query
);

echo "DEBUG SQL[".$SQL_INT."]: =
".$query.";

\n";

$SQL_INT++;

} //SQL_DEBUG


/**
* A wrapper around the mysql_query function.=20
*=20
* Handles the $db handle, errors and echoing of the SQL query itself
* and stores any errors in the global variable errorString;
*
* @access public
* @return result set handle pointer suitable for.
* @param string $sql The SQL query to be executed, this can be SELECT, =
INSERT, UPDATE or DELETE amongst others.
* @param boolean $showSQL output the $sql to the display (for debugging =
purposes usually). false by default.
* @param boolean $showErrors output any errors encountered to the =
display (for debugging purposes usually). true by default.
* @param boolean $execute useful for debuging when you don't want the =
SQL command to actually execute, but you may want to see the query =
passed i.e. SQL_QUERY($sql, true, true, false); true by default.
* @param boolean $noHTML when using the function in console scripts to =
strip off HTML tags.
* @param int $profile detail level (1-3) to output the SQL to =
/tmp/SQL_profile.txt.
* @param int $count The counter used for recursion
* @param string $errorOutput What format the error message, if any, =
should be returned as. Can be txt, xml or html (default).
* @author Daevid Vincent [daevid@]
* @since 3.0
* @version 1.4
* @date 06/04/07
*/
function SQL_QUERY($sql, $showSQL =3D false, $showErrors =3D true, =
$execute =3D true, $noHTML =3D false, $profile =3D 0, $count =3D 0, =
$errorOutput =3D 'html')
{
global $OPTION;
=09
if ($showSQL)=20
{
//[dv] the preg_replace will magically strip out the spaces, newlines, =
tabs and other funky chars to make one nice string.
$sql =3D preg_replace("/\s+/",' ', (preg_replace("/\s/",' ',$sql)) );
=09
if ($OPTION['outfile'])
file_put_contents($OPTION['outfile'], 'SQL: '.$sql."\n", (FILE_APPEND =
| LOCK_EX) );
elseif ($noHTML || $OPTION['noHTML'])
echo "SQL: ".$sql."\n";
else
SQL_DEBUG( $sql );
}
=09
if ($execute)
{
//[dv] added to remove all comments (which may help with SQL =
injections as well.
//$sql =3D preg_replace("/#.*?[\r\n]/s", '', $sql);
//$sql =3D preg_replace("/--.*?[\r\n]/s", '', $sql);
//$sql =3D preg_replace("@/\*(.*?)\*/@s", '', $sql);
=09
// execute query only if it appears to be safe.
if ( ($error_str =3D IS_SAFE_SQL_QUERY($sql)) ===3D TRUE )
{
if ($OPTION['profile'] > 0) $profile =3D $OPTION['profile'];
=09
if ($profile > 0)
$result =3D SQL_PROFILE($sql, $profile);
else
$result =3D @mysql_query($sql,$GLOBALS['__DB_HANDLE']);
} else {
$error =3D "Malformed query (".$error_str."). Execution blocked.";
$result =3D FALSE; // indicate that we failed
}
=09
if (!$result)=20
{
if(!isset($GLOBALS['SQL_ErrorString'])) $GLOBALS['SQL_ErrorString'] =
=3D "";
=09
// if error has not been set, then we have a 'regular' mysql error. =
Otherwise it is a potentially malicious query.
if(!isset($error)){
$error =3D mysql_error($GLOBALS['__DB_HANDLE']);
$errno =3D mysql_errno($GLOBALS['__DB_HANDLE']);
=09
if(($errno == 2013)||($errno == 2006)) {
if($count > 20) {
logger("Maximum number of reconnect attempts =
exceeded, giving up.");
} else {
sleep(2);
if ($errno == 2013)
{
SQL_CONNECT($GLOBALS["__CONNECTED_SERVER"]);
}
elseif ($errno == 2006)
{
SQL_CLOSE();
SQL_CONNECT($GLOBALS["__CONNECTED_SERVER"]);
SQL_DB($GLOBALS['__CURRENT_DB'], false);
}
return SQL_QUERY($sql, $showSQL, $showErrors, =
$execute, $noHTML, $profile, $count + 1, $errorOutput);
}
}
}
else $errno =3D 0; // not 'regular' mysql error? well, we need some =
error code anyway.
=09
// get rid of needlessly verbose MySQL error string
$error =3D preg_replace( '/^You have an error in your SQL =
syntax;.*?near\s*/i', 'Syntax error near ', $error );

// trim to size if necessary
if(!$OPTION['fullQuery'] && strlen( $error ) > 100 )
$error =3D substr( $error, 0, 100 ) . "...";
=09
if ($showErrors && $errorOutput == 'xml' )
{
$GLOBALS['SQL_ErrorString'] .=3D '' . $errno . =
'
' . "\r\n";
$GLOBALS['SQL_ErrorString'] .=3D '' . =
mb_htmlentities($error) . '
' . "\r\n";
$GLOBALS['SQL_ErrorString'] .=3D '' . =
mb_htmlentities($sql) . '
' . "\r\n";
$GLOBALS['SQL_ErrorString'] .=3D '' . =
mb_htmlentities(backtrace(false)) . '
' . "\r\n";
echo $GLOBALS['SQL_ErrorString'];
}
elseif ($showErrors && ( $errorOutput == 'text' || $errorOutput =
== 'txt' ) )
{
$GLOBALS['SQL_ErrorString'] .=3D 'Error Code: ' . $errno . "\n";
$GLOBALS['SQL_ErrorString'] .=3D 'Error Message: ' . $error . =
"\n\n";
$GLOBALS['SQL_ErrorString'] .=3D 'Error SQL: ' . $sql . "\n\n";
$GLOBALS['SQL_ErrorString'] .=3D 'Backtrace: ' . backtrace( =
false, $errorOutput ) . "\n";
echo $GLOBALS['SQL_ErrorString'];
}
elseif ($showErrors)=20
{
$GLOBALS['SQL_ErrorString'] .=3D "SQL ERROR :: =
".$errno." :: ".$error."
SIZE=3D'-3'>".$sql."\n".backtrace(false);
=09
//TODO: [dv] is there a way to determine if we're in a CGI vs. Web =
page?
if ($noHTML or $OPTION['noHTML'])
echo strip_tags($GLOBALS['SQL_ErrorString'])."\n";
else
echo "

padding: 5px;'>
CLASS=3D'error'>".$GLOBALS['SQL_ErrorString']."

\n";
=09
if ($OPTION['outfile'])=09
{
//echo "Dumping error to outfile: ".$OPTION['outfile']."\n";
file_put_contents($OPTION['outfile'], =
strip_tags($GLOBALS['SQL_ErrorString']."\n"), (FILE_APPEND | LOCK_EX) );
}
=09
if ($OPTION['useLogger']) =
logger(strip_tags($GLOBALS['SQL_ErrorString']));
} //if ($showErrors)
} //if (!$result)
=09
return $result;
}=20
=09
return true;
}

/**
* @return int Number of rows in the result set
* @access public
* @author Daevid Vincent [daevid@]
*/
function SQL_NUM_ROWS($rslt)
{
if ($rslt)
return @mysql_num_rows($rslt);
else
return false;
}

/**
* A wrapper around the SQL_QUERY function to return an array of =
key/value pairs.
*=20
* This is very useful for those tables that are simply a key/value and =
you'd like it in an array
* then you can just reference the array and save yourself a JOIN =
perhaps.
*
* @access public
* @return array of key/value pairs.
* @param string $sql The SQL query to be executed, this can be SELECT, =
INSERT, UPDATE or DELETE amongst others.
* @param boolean $showSQL output the $sql to the display (for debugging =
purposes usually). false by default.
* @param boolean $showErrors output any errors encountered to the =
display (for debugging purposes usually). true by default.
* @param boolean $execute useful for debuging when you don't want the =
SQL command to actually execute, but you may want to see the query =
passed i.e. SQL_QUERY($sql, true, true, false); true by default.
* @param boolean $noHTML when using the function in console scripts to =
strip off HTML tags.
* @param int $profile detail level (1-3) to output the SQL to =
/tmp/SQL_profile.txt.
* @param int $count The counter used for recursion
* @param string $errorOutput What format the error message, if any, =
should be returned as. Can be txt, xml or html (default).
* @author Daevid Vincent [daevid@]
* @since 3.0
* @version 1.0
* @date 07/29/04
*/
function SQL_QUERY_ARRAY_PAIR($sql, $showSQL =3D false, $showErrors =3D =
true, $execute =3D true, $noHTML =3D false, $profile =3D 0, $count =3D =
0, $errorOutput =3D 'html')
{
$rslt =3D SQL_QUERY($sql, $showSQL, $showErrors, $execute, $noHTML, =
$profile, $count, $errorOutput);
if ($rslt)
{
while(list($key,$value) =3D SQL_ROW($rslt))
$tmpArray[$key] =3D $value;
return $tmpArray;
}
return false;
}

/**
* @return array Single element assoc. array
* @access public
* @author Daevid Vincent [daevid@]
*/
function SQL_ASSOC_ARRAY($rslt)
{
if ($rslt)
return @mysql_fetch_assoc($rslt);
else
return false;
}

/**
* @return array Single element array
* @access public
* @author Daevid Vincent [daevid@]
*/
function SQL_ROW($rslt)
{
if ($rslt)
return @mysql_fetch_row($rslt);
else
return false;
}

/**
* @return string Returns the correct view for the current locale
* @param string $locale The locale to look up=20
* @param bool $check Whether to check if the table/view exists. If =
not, use default table
* @access public
*/
function SQL_VIEW_LOCALE($table, $locale =3D null, $check =3D true)
{
$view =3D $table;
if (is_null($locale))
{
if(isset($_SESSION['oplocale']))
$locale =3D $_SESSION['oplocale'];
}
=09
switch($locale)
{
case 'en':
case 'en_US':
case 'en_US.utf8':
$view .=3D '_en_US';
break;
case 'en_GOV':
case 'en_GOV.utf8':
$view .=3D '_en_GOV';
break;
case 'ja':
case 'ja_JP':
case 'ja_JP.utf8':
$view .=3D '_ja_JP';
break;
}
=09
//important: Either a DB resource must already be set, or the database =
needs to
//be in the table name for this to work correctly;
if ($check)
{
$try =3D SQL_QUERY('SELECT 1 FROM '.$view.' LIMIT 1', false, false);
if (!$try) $view =3D $table; //set back to default if view does not =
exist
}
=09
return $view;
}

/**
* @access public
* @author Daevid Vincent [daevid@]
*/
function SQL_RESULT($rslt, $row =3D 0)
{
if ($rslt)
return @mysql_result($rslt, $row);
else
return false;
}

/**
* @return int Insert ID of last insert action=20
* @access public
* @author Daevid Vincent [daevid@]
*/
function SQL_INSERT_ID()
{
return @mysql_insert_id($GLOBALS['__DB_HANDLE']);
}

/**
* @return int Number of affected rows
* @access public
* @author Daevid Vincent [daevid@]
*/
function SQL_AFFECTED_ROWS()
{
return @mysql_affected_rows($GLOBALS['__DB_HANDLE']);
}

/**
* Free up a mysql pointer
* @access public
* @author Daevid Vincent [daevid@]
*/
function SQL_FREE($rslt)
{
if ($rslt)
return @mysql_free_result($rslt);
else
return false;
}

/**
* @access public
* @author Daevid Vincent [daevid@]
*/
function SQL_ESCAPE($s, $trim =3D true)
{
if( is_array( $s ) )
foreach( $s as $k =3D> $v )
$escaped[$k] =3D SQL_ESCAPE( $v, $trim );
else
$escaped =3D mysql_real_escape_string( $trim ? trim( $s ) : $s );

return( $escaped );
}

/**
* Seek the pointer
* @access public
* @author Daevid Vincent [daevid@]
*/
function SQL_DATA_SEEK($rslt, $row =3D 0)
{
return mysql_data_seek($rslt, $row);
}

/**
* @return int MySQL error number
* @access public
* @author Daevid Vincent [daevid@]
*/
function SQL_ERROR_NUM()
{
return @mysql_errno($GLOBALS['__DB_HANDLE']);
}

/**
* @return int MySQL error message
* @access public
* @author Daevid Vincent [daevid@]
*/
function SQL_ERROR()
{
return @mysql_error($GLOBALS['__DB_HANDLE']);
}

/**
* Close out the connection to the SQL server
* @access public
* @author Daevid Vincent [daevid@]
*/
function SQL_CLOSE()
{
return @mysql_close($GLOBALS['__DB_HANDLE']);
}

/**
* This returns error 1007 if it exists already, SQL_ERROR supressed
* @access public
* @author Daevid Vincent [daevid@]
*/
function SQL_CREATE_DB($name)
{
//[dv] depricated and not even included in our build of PHP!?
//http://us2.php.net/manual/en/function.mysql-create-db.php
//return mysql_create_db($name, $db);
=09
//[dv] this is not a good way to do this, as it doesn't tell you if it =
succeeded or not.
//return SQL_QUERY("CREATE DATABASE IF NOT EXISTS ".$name);
=09
//this returns error 1007 if it exists already, SQL_ERROR supressed
return SQL_QUERY("CREATE DATABASE ".$name, false, false);
}

/**
* Returns the value of the given field in the database.
*=20
* it's annoying to have to do this to find out the username given their =
ID,
* or other tedious times when you simply need a quick value in a lookup =
table
*
* @access public
* @return the number of rows in the SELECT box.
* @param $id the record id for which to retrieve the data
* @param $pk the column to use the $id in. usually the primary key.
* @param $column the column name's value to retrieve.
* @param $dbtable which table (or db.table) does this reside in.
* @author Daevid Vincent [daevid@]
* @since 3.0
* @version 1.0
* @date 07/12/04
*/
function SQL_getField($id, $pk, $column, $dbtable)
{
$sth =3D SQL_QUERY("SELECT ".$column." FROM ".$dbtable." WHERE ".$pk." =
=3D '".$id."' LIMIT 1");
if ($sth)=20
{
$r =3D SQL_ASSOC_ARRAY($sth);
return $r[$column];
}
return false;
}

/**
* Dynamically generates a select box from a SQL query.=20
*=20
* The SELECT must return between one and three items.=20
* first is the VALUE the second is the text to display and optional =
third is shown in parenthesis
* if there is only a VALUE, then that is used as the display text too.
* form element prefilled in
*
* Tooltips do NOT work in IE. sorry. blame Microsoft for not following =
W3 standards...
*
* @access public
* @return the number of rows in the SELECT box or false.
* @param $size usually 1, but the select box can be any height.
* @param $name the NAME=3D'$name' parameter of a SELECT tag.
* @param $sql The actual SQL SELECT query that returns between 2 and 3 =
columns.
* @param $blank add the extra 'empty' "; }
elseif ($blank && is_string($blank)) { echo ""; }
while (@list($key, $text, $description) =3D SQL_ROW($qry))
{
$items++;
=09
// Check for selectbox sub-headings.
if ( 0 == strncmp( $text, "---", 3 ) )
{
echo "\n";
}
}
}
=09
echo "\t\n";
=09
SQL_FREE($qry);
return $items;
}
else echo "select box cannot be built because of an invalid SQL =
query.\n";
=09
SQL_FREE($qry);
return false;
} // end SelectBoxSQL

/**
* returns a string that can be appended to an SQL statement to form the =
ORDER BY portion.
*
* if you want to sort by 'service' in descending order, then simply use =
'service_DESC',
* conversely, 'service_ASC' would sort in ascending order. The order of =
the elements in the array
* will determine the order they are appended together.
*
* @access public
* @return string of the form ' ORDER BY element[1], element[2], =
element[3]'...
* @param $orderBy false, string, or array of elements like so: =
[sort_by] =3D> Array ( [1] =3D> service_DESC [2] =3D> protocol [3] =3D> =
port )=20
* @param $default a string to use as the default ORDER BY column
* @since Alcatraz
* @version 1.1
* @date 01/18/05
*/
function parseOrderByArray($orderBy =3D false, $default =3D false)
{
$sql =3D ' ORDER BY ';
=09
if (!is_array($orderBy))
{
//[dv] is_string() is not enough, as empty values are coming across as =
strings according to var_dump()
if (strlen($orderBy) > 1)=20
return $sql.$orderBy;
elseif (is_string($default))
return $sql.$default;
else=20
return false;
}
=09
foreach ($orderBy as $o)
$tmp[] =3D str_replace('_', ' ', $o);
=09
return $sql.implode(', ',$tmp);
}

/**
* returns an array of ENUM values from a table/column.
*
* @access public
* @return array of enum values
* @param string $Table the name of the table to query
* @param string $Column the name of the enum column to query
* @param boolean $sorted by default the results are sorted otherwise =
they are in the order of the enum schema
* @param boolean $indexed by default the key/value are the same string. =
if true, then key is an integer.
* @since 4.2
* @version 1.0
* @date 01/26/06
* @see SelectBoxArray()
*/
function SQL_getEnumValues($Table, $Column, $sorted =3D true, $indexed =
=3D false)
{
if ($dbQuery =3D SQL_QUERY("SHOW COLUMNS FROM ".$Table." LIKE =
'".$Column."'"))
{
$EnumArray =3D array();
=09
$dbRow =3D SQL_ASSOC_ARRAY($dbQuery);
$EnumValues =3D $dbRow['Type'];
=09
$EnumValues =3D substr($EnumValues, 6, strlen($EnumValues)-8);=20
$EnumValues =3D str_replace("','",",",$EnumValues);
=09
if ($indexed)
{
$EnumArray =3D explode(",",$EnumValues);
if ($sorted) sort($EnumArray);
}
else
{
$tmp =3D explode(",",$EnumValues);
foreach($tmp as $k =3D> $v) $EnumArray[$v] =3D $v;
if ($sorted) ksort($EnumArray);
}
=09
return $EnumArray;
}
return false;
}

//these functions are more ENUM related ones that are currently unused, =
but may be useful at a later date...
/*
function SelectBoxEnum($table)
{
$describe=3DSQL_QUERY("describe ".$table);
while ($ligne=3DSQL_ASSOC_ARRAY($describe))
{
extract($ligne);
if (substr($Type,0,4)=='enum')
{
echo $Type;
$liste=3Dsubstr($Type,5,strlen($Type));
$liste=3Dsubstr($liste,0,(strlen($liste)-2));
$enums=3Dexplode(',',$liste);
if (sizeof($enums) > 0)
{
echo "";
}
}
}
}

function SSM_inputEnumDBField( $myName, $myTable, $myField, =
$myDefault=3D"", $visible=3Dtrue )
{
// query the DB to extract the enum values
$qqq =3D "DESCRIBE $myTable $myField";
$result =3D SQL_QUERY( $qqq );
$arow =3D SQL_ASSOC_ARRAY( $result );
$myArr =3D explode( ",", trim( strstr( $arow['Type'], "(" ), =
"()")) ;
=09
// now format the values as required by SSM_inputSelect()
$idx =3D 0;
$cnt =3D count($myArr);
while($idx < $cnt)
{
$myArr[$idx] =3D trim( $myArr[$idx], "'" );
$idx++;
}
sort( $myArr );
$myList =3D implode( "|", $myArr );
return SSM_inputSelect( $myName, $myList, $myDefault );
}
*/

/**
* Generates an HTML formatted backtrace to pinpoint exactly where code =
STB.=20
*=20
* taken from the PHP user supplied functions as adodb_backtrace()
* shows the functions, file:// and line #
* this is not database specific, i only include it here for convenience =
as this is included on every page,
* and more often than not, your SQL is what barfs, moreso than any other =
function...
*
* @access public
* @return an HTML formatted string complete with file, function and =
line that barfed
* @param $print defaults to true, but can be false if you just want the =
returned string.
* @param $output The type of output that is returned. Default is HTML.
* @author [jlim@natsoft.com.my]
* @since 3.0
* @version 1.1
* @date 09/15/04
*/
function backtrace($print =3D true, $output =3D 'html')
{
global $SQL_ERROR_COUNT;
if( !isset($SQL_ERROR_COUNT) ) $SQL_ERROR_COUNT =3D 0;

$s =3D '';
$MAXSTRLEN =3D 64;
$s =3D ( $ouptut == 'html' ? "\n
CLASS=3D'error'>" : '' ) . 'BACKTRACE' . ( $ouptut == 'html' ? =
"
" : '' ) . " ::\n";
$traceArr =3D debug_backtrace();
array_shift($traceArr);
$tabs =3D sizeof($traceArr)-1;
foreach ($traceArr as $arr)=20
{
for ($i=3D0; $i < $tabs; $i++) $s .=3D ( $output == 'html' ? ' =
  ' : ' ' );
$tabs -=3D 1;
//$s .=3D "";
if (isset($arr['class'])) $s .=3D $arr['class'].'.';
if (isset($arr['args']) && is_array($arr['args']))
foreach($arr['args'] as $v)=20
{
if (is_null($v)) $args[] =3D 'null';
else if (is_array($v)) $args[] =3D 'Array['.sizeof($v).']';
else if (is_object($v)) $args[] =3D 'Object:'.get_class($v);
else if (is_bool($v)) $args[] =3D $v ? 'true' : 'false';
else {=20
$v =3D (string) @$v;
$str =3D ( $output == 'html' ? =
htmlspecialchars(substr($v,0,$MAXSTRLEN)) : substr($v,0,$MAXSTRLEN) );
if (strlen($v) > $MAXSTRLEN) $str .=3D '...';
$args[] =3D $str;
}
}
=09
if (isset($arr['args']) && is_array($args))
$s .=3D ( $output == 'html' ? '' : '' ) . $arr['function'] . =
'(' . ( $output == 'html' ? '
' : '' ) . implode( ', ', $args ) . =
( $output == 'html' ? '' : '' ) . ')' . ( $output == 'html' ? =
'
' : '' );
//$s .=3D ( $output == 'html' ? '
' : '' );
if( $output == 'html' )
$s .=3D sprintf(" :: line #%d,"." =
file: href=3D\"file:/%s\">%s
",$arr['line'],$arr['file'],$arr['file']=
);
else
$s .=3D sprintf(" :: line #%d, file: %s", $arr['line'], $arr['file'] =
);
$s .=3D "\n";
}=20
$s .=3D ( $output == 'html' ? "
\n" : '' );
if ($print) print $s;
=09
if($SQL_ERROR_COUNT++ > MAX_SQL_ERRORS) exit( ( $output == 'html' ? =
'

' : '' ) . '*** More than ' . MAX_SQL_ERRORS . ' SQL =
errors. Aborting script. ***' . ( $output == 'html' ? =
'

' : '' ) );
=09
return $s;
} //backtrace()

/**
* @access public
*/
function update_plugin_cache($company){
update_unsafe_tests($company);
}

/**
* @access public
*/
function update_unsafe_tests($company) {
SQL_QUERY("REPLACE INTO $company.testset SELECT * from V2_Data.testset =
WHERE id < 1000");
SQL_QUERY("DELETE=20
FROM $company.testset_test
WHERE testset_id =3D 3");
SQL_QUERY("INSERT=20
INTO $company.testset_test
(SELECT NULL, 3, scan_id=20
FROM Swordfish.pluginlist
WHERE category IN (3,5,8) OR=20
scan_id IN (11475) OR=20
name LIKE '%crashes%' OR=20
summary LIKE '%crashes%')");
}

/**
* @access public
*/
function guideTableDB($Key, $Attribute=3D"", $Type=3D"4")
{=09
$Key =3D trim($Key, "/");
$query =3D SQL_QUERY("SELECT html FROM =
".SQL_VIEW_LOCALE('Swordfish.ld_guide')." WHERE gui_key =3D '".$Key."' =
AND gui_key_type =3D '".$Type."' LIMIT 1");
if ($query) $data =3D SQL_ROW($query);
$content =3D $data[0];
if ($content !=3D '')=20
{
$content =3D eregi_replace("h[0-9]>", "b>", $content);
$content =3D eregi_replace("[0-9]+\..nbsp;", "
  • ", $content);
    $content =3D eregi_replace(".nbsp;", " ", $content);
    $content =3D eregi_replace("[\r\n ]+

      \r\r

      $content);
      $content =3D $content."

    ";
    ?>



    $Attribute ?>>







    CLASS=3D"tableHeadline">

      instructions may disappear once data is populated on this page. To view =
      this again, click the button =
      in the upper-right corner of the screen.')?>


    =09


    }
    }

    /**
    * Prepare a sql query
    * @author krogebry (krogebry@)
    * @param string $sql SQL query
    * @returns dbObject object
    */
    function SQL_PREPARE( $sql, $debug=3Dfalse )
    {
    return new dbObject($sql, $debug);
    }// SQL_PREPARE()

    /**
    * Prepared DB object.
    * This is what gets passed back from SQL_PREPARE()
    * Usage:
    * Use just about the same way that perl DBI, or any other high level=20
    * DB abstraction layer works. Use '?' as the replacement key.
    * Example:
    * $sql =3D "SELECT * FROM blah WHERE id=3D?";
    * $ptr =3D SQL_PREPARE( $sql );
    * for( $i=3D0; $i<10; $i++ ){
    * $ro =3D $ptr->execute( array($i) );
    * print_x( $ro );
    * }
    *
    * Notes:
    * execute simply replaces ? with it's value enclosed in "",
    * then returns SQL_QUERY(QUERY)
    */
    class dbObject
    {
    /** Variables */
    /** @var $sql SQL query */
    private $sql =3D "";

    /** @var $sql SQL query */
    private $numMatches =3D 0;
    private $debug =3D 0;
    private $ptr =3D "";
    /** End Variables */

    public function __construct($sql, $debug=3Dfalse) {
    $num =3D preg_match_all( "/\?/", $sql, $matches );
    $this->numMatches =3D $num;
    $this->sql =3D $sql;
    $this->debug =3D $debug;
    }// __construct()

    /**
    * Execute the prepared sql query
    * @param array $array Array of replacement values
    */
    public function execute( $array, $debug=3Dfalse ) {
    if( sizeof($array) !=3D $this->numMatches )=20
    throw new SQL_EXCEPTION("Invalid matching params for query =
    [".sizeof($array) ."]::[". $this->numMatches ."]");

    $sql =3D $this->sql;

    foreach($array as $a ) {
    $sql =3D preg_replace( "/\?/", "\"". $a ."\"", $sql, 1 );
    }

    if( $debug==true || $this->debug==true ){
    SQL_DEBUG( $sql );
    }

    if( !$ptr =3D SQL_QUERY($sql,$this->debug) ){
    throw new SQL_EXCEPTION( $sql );
    }else{
    $this->ptr =3D $ptr;
    return $ptr;
    }

    }// execute()
    =09
    public function numRows(){ return SQL_NUM_ROWS( $this->ptr ); }
    public function fetchrow(){ return SQL_ASSOC_ARRAY( $this->ptr ); }
    }// dbObject



    class SQL_EXCEPTION extends Exception
    {
    private $sql =3D "";
    private $debug =3D "";
    private $die =3D false;
    =09
    public function __construct( $sql=3D"", $debug=3D"", $die=3Dfalse )
    {
    $this->sql =3D $sql;
    $this->debug =3D $debug;
    $this->die =3D $die;
    }
    =09
    public function getQuery(){ return $this->sql; }
    public function getDebug(){ return $this->debug; }
    =09
    public function dump( $verbosity=3D1 ){
    $trace =3D $this->getTrace();
    #print_x( $trace );
    ?>




    getQuery()?>
    getDebug()?>






    }

    }// SQL_EXCEPTION=20


    //found here http://us2.php.net/manual/en/function.split.php
    function quotesplit( $s, $splitter =3D ' ', $restore_quotes =3D 0 )=20
    {=20
    $s =3D str_replace('""', "'", $s);=20
    =20
    $getstrings =3D explode('"', $splitter.$s.$splitter);=20

    $delimlen =3D strlen($splitter);=20
    $instring =3D 0;=20

    while (list($arg, $val) =3D each($getstrings))=20
    {=20
    if ($instring==1)=20
    {=20
    if( $restore_quotes ) =20
    $result[count($result)-1] =3D =
    $result[count($result)-1].'"'.$val.'"'; =20
    else=20
    $result[] =3D $val;=20
    $instring =3D 0;=20
    }=20
    else=20
    {=20
    if ((strlen($val)-$delimlen) >=3D 1)=20
    {=20
    $temparray =3D split($splitter, substr($val, $delimlen, =
    strlen($val)-$delimlen-$delimlen ) );=20
    while(list($iarg, $ival) =3D each($temparray))=20
    {=20
    $result[] =3D trim($ival);=20
    }=20
    }=20
    $instring =3D 1;=20
    }=20
    }=20
    return $result;=20
    }=20
    ?>


    ------=_NextPart_000_0125_01CA5BE5.B81AC140
    Content-Type: text/plain; charset=us-ascii

    --
    PHP General Mailing List (http://www.php.net/)
    To unsubscribe, visit: http://www.php.net/unsub.php
    ------=_NextPart_000_0125_01CA5BE5.B81AC140--

  • Re: Custom function for inserting values into MySQL

    am 03.11.2009 03:07:31 von Phpster

    I would take a look at some of the frameworks like codeignter to see
    how they do things.

    But like Davied mentioned a simpler way to handle the passing into the
    function would be

    Function save($table, $data)


    Where data is an array of key value pairs which takes your 22
    parameters down to 2.

    The array could look like

    $data = array('id' => 1, 'name' => 'bob' ...)

    Bastien

    Sent from my iPod

    On Nov 2, 2009, at 8:32 PM, Allen McCabe wrote:

    > Okay friends, I have been wondering about writing a simple function
    > that
    > will help me with my MySQL inserting. Not because I need to save
    > time and
    > space, but because I wanted to.
    >
    > I wrote a function for inserting 10 values (I have not been able to
    > come up
    > with an idea how to make the number of values I'm inserting
    > variable, so I'm
    > sticking with ten).
    >
    > This function takes 22 parameters: #1 is the table name, #2-21 are
    > the row
    > names and the values, and #22 is the "integar string".
    >
    > The first 21 parameters are self-explanatory, the 22nd is a string
    > of values
    > that need to be inserted as an integar, basically, not adding single
    > quotes
    > around the value. Eg. $value2 = 5, not $value2 = '5'.
    >
    > I am very hesitant to try this one out on my database, I've got
    > tables of
    > important information and don't want to, I don't know, inadvertantly
    > throw a
    > wrench into the works, AND I want to open up a dialoug about custom
    > PHP
    > functions for working with MySQL, for the fun of it!
    >
    > Here is my 10 value function for inserting data into a MySQL
    > database table.
    >
    > function insertinto10($table, $field1, $value1, $field2, $value2,
    > $field3,
    > $value3, $field4, $value4, $field5, $value5, $field6, $value6,
    > $field7,
    > $value7, $field8, $value8, $field9, $value9, $field10, $value10,
    > $int =
    > NULL)
    > {
    > if (isset($int))
    > {
    > $sPattern = '/\s*/m';
    > $sReplace = '';
    > $int = preg_replace($sPattern, $sReplace, $int);
    > $pieces = explode(",", $int); // $pieces[0], $pieces[1] - each
    > equal to
    > value numbers that are integars
    > $length = count($pieces);
    > // call custom function to create associative array eg. $newarray
    > [2] = 1,
    > $newarray[4] = 1, $newarray[5] = 1 . . .
    > $integarArray = strtoarray($length, $int);
    > }
    >
    > $valuesArray = array($value1, $value2, $value3, $value4, $value5,
    > $value6,
    > $value7, $value8, $value9, $value10);
    >
    > foreach ($valuesArray as $key => $value)
    > {
    > if (isset($integarArray[$key]) && $integarArray[$key] == 1)
    > {
    > // INTEGAR VALUE
    > $valuesArray[$key] = mysql_real_escape_string(stripslashes($value));
    > }
    > else
    > {
    > // STRING VALUE
    > $cleanValue = mysql_real_escape_string(stripslashes($value));
    > $valuesArray[$key] = "'{$cleanValue}'";
    > }
    > }
    >
    > $result = mysql_query("INSERT INTO `{$table}` (`{$field1}`, `
    > {$field2}`,
    > `{$field3}`, `{$field4}`) VALUES ({$valuesArray[1]}, {$valuesArray
    > [2]},
    > {$valuesArray[3]}, {$valuesArray[4]}, {$valuesArray[5]},
    > {$valuesArray[6]},
    > {$valuesArray[7]}, {$valuesArray[8]}, {$valuesArray[9]},
    > {$valuesArray[10]})");
    > return $result;
    > }
    >
    >
    > You may find copying/pasting into your favorite code-editor helps
    > make it
    > more readable.
    >
    > Do you see any major hangups or screwups on first glance? And is my
    > fear of
    > trying this out on my database unfounded? Does this even seem that
    > useful?

    --
    PHP General Mailing List (http://www.php.net/)
    To unsubscribe, visit: http://www.php.net/unsub.php

    Re: Custom function for inserting values into MySQL

    am 03.11.2009 15:54:28 von Shawn McKenzie

    Allen McCabe wrote:
    > Okay friends, I have been wondering about writing a simple function that
    > will help me with my MySQL inserting. Not because I need to save time and
    > space, but because I wanted to.
    >
    > I wrote a function for inserting 10 values (I have not been able to come up
    > with an idea how to make the number of values I'm inserting variable, so I'm
    > sticking with ten).
    >
    > This function takes 22 parameters: #1 is the table name, #2-21 are the row
    > names and the values, and #22 is the "integar string".
    >
    > The first 21 parameters are self-explanatory, the 22nd is a string of values
    > that need to be inserted as an integar, basically, not adding single quotes
    > around the value. Eg. $value2 = 5, not $value2 = '5'.
    >
    > I am very hesitant to try this one out on my database, I've got tables of
    > important information and don't want to, I don't know, inadvertantly throw a
    > wrench into the works, AND I want to open up a dialoug about custom PHP
    > functions for working with MySQL, for the fun of it!
    >
    > Here is my 10 value function for inserting data into a MySQL database table.
    >
    > function insertinto10($table, $field1, $value1, $field2, $value2, $field3,
    > $value3, $field4, $value4, $field5, $value5, $field6, $value6, $field7,
    > $value7, $field8, $value8, $field9, $value9, $field10, $value10, $int =
    > NULL)
    > {
    > if (isset($int))
    > {
    > $sPattern = '/\s*/m';
    > $sReplace = '';
    > $int = preg_replace($sPattern, $sReplace, $int);
    > $pieces = explode(",", $int); // $pieces[0], $pieces[1] - each equal to
    > value numbers that are integars
    > $length = count($pieces);
    > // call custom function to create associative array eg. $newarray[2] = 1,
    > $newarray[4] = 1, $newarray[5] = 1 . . .
    > $integarArray = strtoarray($length, $int);
    > }
    >
    > $valuesArray = array($value1, $value2, $value3, $value4, $value5, $value6,
    > $value7, $value8, $value9, $value10);
    >
    > foreach ($valuesArray as $key => $value)
    > {
    > if (isset($integarArray[$key]) && $integarArray[$key] == 1)
    > {
    > // INTEGAR VALUE
    > $valuesArray[$key] = mysql_real_escape_string(stripslashes($value));
    > }
    > else
    > {
    > // STRING VALUE
    > $cleanValue = mysql_real_escape_string(stripslashes($value));
    > $valuesArray[$key] = "'{$cleanValue}'";
    > }
    > }
    >
    > $result = mysql_query("INSERT INTO `{$table}` (`{$field1}`, `{$field2}`,
    > `{$field3}`, `{$field4}`) VALUES ({$valuesArray[1]}, {$valuesArray[2]},
    > {$valuesArray[3]}, {$valuesArray[4]}, {$valuesArray[5]}, {$valuesArray[6]},
    > {$valuesArray[7]}, {$valuesArray[8]}, {$valuesArray[9]},
    > {$valuesArray[10]})");
    > return $result;
    > }
    >
    >
    > You may find copying/pasting into your favorite code-editor helps make it
    > more readable.
    >
    > Do you see any major hangups or screwups on first glance? And is my fear of
    > trying this out on my database unfounded? Does this even seem that useful?
    >

    I'll echo what the others have said about the parameters. For me
    personally, if I am passing more than three parameters (sometimes even
    three) I rethink my function. I'm not sure what you envision using this
    function for, but the approach I use for forms and databases is always
    arrays. I get an array from my forms, I insert that array into the
    database, and of course I fetch arrays out of the database. These are
    all indexed the same with the index as the field name of the table so
    it's easy.


    --
    Thanks!
    -Shawn
    http://www.spidean.com

    --
    PHP General Mailing List (http://www.php.net/)
    To unsubscribe, visit: http://www.php.net/unsub.php

    Re: Custom function for inserting values into MySQL

    am 04.11.2009 15:19:58 von Shawn McKenzie

    In your example, I would name my form inputs similar to name
    ="data[user_id]".

    Then you just pass the $_POST['data'] array to your function.

    -Shawn

    Allen McCabe wrote:
    > You raise some good points. I always name my input fields after the
    > entity names ( eg. input type="hidden" name ="user_id" value=" ?php
    > echo $resultRow['user_id'] ? " ).
    >
    > I suppose I am still in the phase of learning efficiency, and perhaps
    > trying to 'get out it' by writing functions that I can just call and
    > pass parameters instead of fully learning the core concepts.
    >
    > I just think functions are so damn cool :)
    >
    >
    > I'll echo what the others have said about the parameters. For me
    > personally, if I am passing more than three parameters (sometimes even
    > three) I rethink my function. I'm not sure what you envision
    > using this
    > function for, but the approach I use for forms and databases is always
    > arrays. I get an array from my forms, I insert that array into the
    > database, and of course I fetch arrays out of the database. These are
    > all indexed the same with the index as the field name of the table so
    > it's easy.
    >
    >
    > --
    > Thanks!
    > -Shawn
    > http://www.spidean.com
    >
    >
    >

    --
    PHP General Mailing List (http://www.php.net/)
    To unsubscribe, visit: http://www.php.net/unsub.php

    Re: Custom function for inserting values into MySQL

    am 04.11.2009 17:07:04 von Nathan Rixham

    Shawn McKenzie wrote:
    > Allen McCabe wrote:
    >>
    >> Do you see any major hangups or screwups on first glance? And is my fear of
    >> trying this out on my database unfounded? Does this even seem that useful?
    >>

    in all honesty.. loads of screwups - don't try it out on your database &
    ultimately if it isn't re-usable then it isn't useful (and it's isn't
    re-usable unless every single table you have is the same.. which they
    aren't)

    to be a bit more constructive though.. this is a road most developers
    have been down, and well known solutions already exist.

    You've got two choices..

    1] continue down this route and learn as you go (but for god sake get a
    test database) - recommended if you really want to learn not just PHP
    but programming in general; once you understand it all you can go
    looking at design patterns, common solutions and how other people do it
    and have enough knowledge to make informed decisions.

    2] just use what's made and don't think too much about it, you'll be
    productive and can throw in support/help requests whenever it goes
    wrong, works for some people.. to do this get a decent framework and
    read it's manual (or use pdo, or an ORM for PHP or something)

    all depends on what you want, how much time you have, and where you want
    to end up.

    --
    PHP General Mailing List (http://www.php.net/)
    To unsubscribe, visit: http://www.php.net/unsub.php

    RE: Custom function for inserting values into MySQL

    am 04.11.2009 22:51:47 von Daevid Vincent

    > -----Original Message-----
    > From: Shawn McKenzie [mailto:nospam@mckenzies.net]
    > Sent: Wednesday, November 04, 2009 6:20 AM
    > To: Allen McCabe; PHP General
    > Subject: Re: [PHP] Custom function for inserting values into MySQL
    >
    > In your example, I would name my form inputs similar to name
    > ="data[user_id]".
    >
    > Then you just pass the $_POST['data'] array to your function.
    >
    > -Shawn
    >
    > Allen McCabe wrote:
    > > You raise some good points. I always name my input fields after the
    > > entity names ( eg. input type="hidden" name ="user_id" value=" ?php
    > > echo $resultRow['user_id'] ? " ).
    > >
    > > I suppose I am still in the phase of learning efficiency,
    > and perhaps
    > > trying to 'get out it' by writing functions that I can just call and
    > > pass parameters instead of fully learning the core concepts.
    > >
    > > I just think functions are so damn cool :)
    > >
    > >
    > > I'll echo what the others have said about the
    > parameters. For me
    > > personally, if I am passing more than three parameters
    > (sometimes even
    > > three) I rethink my function. I'm not sure what you envision
    > > using this
    > > function for, but the approach I use for forms and
    > databases is always
    > > arrays. I get an array from my forms, I insert that
    > array into the
    > > database, and of course I fetch arrays out of the
    > database. These are
    > > all indexed the same with the index as the field name
    > of the table so
    > > it's easy.
    > >
    > >
    > > --
    > > Thanks!
    > > -Shawn
    > > http://www.spidean.com
    > >
    > >
    > >

    There are pro's and cons to this type of thing. In general that is how I do
    it too, but you have to be aware of security and organization. It's not
    always smart to expose your DB field names directly so you might want to
    obscure them for some critical values. If your passing from one controlled
    function/method to another then this isnt an issue so much.

    I also follow the ruby/rails ideal where tables are plural names ("users")
    and classes are singular names ("user.class.php"). Tables always have fields
    for 'id','created_on','timestamp','enabled'. Except in 'glue table' cases
    (1:n or n:m). Classes extend a base class which handles a lot of the minutea
    including the magic __get() and __set() routines as well as knowing what
    table they should be through introspection (ie. Their own file name).

    No need to name your fields as arrays. $_POST is already an array. You've
    just added more complexity/dimensions. When you submit your form just pass
    $_POST to your function instead. In the function, is where you should do any
    normalizing, scrubbing and unsetting (as per good MVC ideology)...

    In your page form:

    if ($_POST['submit'] == 'Update')
    {
    $result = process_data($_POST);
    }

    Then in some include file somewhere (here is a simplified example of
    course):

    function process_data($data)
    {
    //perhaps you don't care about the submit button
    unset($data['submit']);

    //maybe you don't want everyone to know your DB schema
    //so you re-map from form element names to DB fields...
    $data['user_id'] = $data['uid'];
    unset($data['uid']);

    //strip white space off
    foreach ($data as $k => $v) $data[$k] = trim($v);

    //do validity checking of each important data item
    if (intval($data['user_id']) < 1) return false;

    //any other pre-processing

    //do interesting stuff here with scrubbed $data array now
    sql_query('UPDATE mytable SET ...... WHERE user_id = '.$data['user_id'].'
    LIMIT 1');

    //of course, I would use a routine that builds the update / insert
    statements from
    //the array key/value pairs -- see previous attached example
    base.class.php in this thread.
    }

    http://daevid.com


    --
    PHP General Mailing List (http://www.php.net/)
    To unsubscribe, visit: http://www.php.net/unsub.php

    Re: Custom function for inserting values into MySQL

    am 05.11.2009 01:58:54 von Shawn McKenzie

    Daevid Vincent wrote:
    >> -----Original Message-----
    >> From: Shawn McKenzie [mailto:nospam@mckenzies.net]
    >> Sent: Wednesday, November 04, 2009 6:20 AM
    >> To: Allen McCabe; PHP General
    >> Subject: Re: [PHP] Custom function for inserting values into MySQL
    >>
    >> In your example, I would name my form inputs similar to name
    >> ="data[user_id]".
    >>
    >> Then you just pass the $_POST['data'] array to your function.
    >>
    >> -Shawn
    >>
    >> Allen McCabe wrote:
    >>> You raise some good points. I always name my input fields after the
    >>> entity names ( eg. input type="hidden" name ="user_id" value=" ?php
    >>> echo $resultRow['user_id'] ? " ).
    >>>
    >>> I suppose I am still in the phase of learning efficiency,
    >> and perhaps
    >>> trying to 'get out it' by writing functions that I can just call and
    >>> pass parameters instead of fully learning the core concepts.
    >>>
    >>> I just think functions are so damn cool :)
    >>>
    >>>
    >>> I'll echo what the others have said about the
    >> parameters. For me
    >>> personally, if I am passing more than three parameters
    >> (sometimes even
    >>> three) I rethink my function. I'm not sure what you envision
    >>> using this
    >>> function for, but the approach I use for forms and
    >> databases is always
    >>> arrays. I get an array from my forms, I insert that
    >> array into the
    >>> database, and of course I fetch arrays out of the
    >> database. These are
    >>> all indexed the same with the index as the field name
    >> of the table so
    >>> it's easy.
    >>>
    >>>
    >>> --
    >>> Thanks!
    >>> -Shawn
    >>> http://www.spidean.com
    >>>
    >>>
    >>>
    >
    > There are pro's and cons to this type of thing. In general that is how I do
    > it too, but you have to be aware of security and organization. It's not
    > always smart to expose your DB field names directly so you might want to
    > obscure them for some critical values. If your passing from one controlled
    > function/method to another then this isnt an issue so much.
    >
    > I also follow the ruby/rails ideal where tables are plural names ("users")
    > and classes are singular names ("user.class.php"). Tables always have fields
    > for 'id','created_on','timestamp','enabled'. Except in 'glue table' cases
    > (1:n or n:m). Classes extend a base class which handles a lot of the minutea
    > including the magic __get() and __set() routines as well as knowing what
    > table they should be through introspection (ie. Their own file name).
    >
    > No need to name your fields as arrays. $_POST is already an array. You've
    > just added more complexity/dimensions. When you submit your form just pass
    > $_POST to your function instead. In the function, is where you should do any
    > normalizing, scrubbing and unsetting (as per good MVC ideology)...
    >

    The way I normally do it I learned from the CakePHP framework which is
    very similar to (I think an attempt at a clone of) Rails. I'm not sure
    if they do it the same way in Rails, but as you were mentioning, in a
    Cake view of a form they use the table name as the array name
    (name="Users[username]"). Internally to the framework this may make
    things easier, but imagine you have a page with 2 or more forms that
    update different tables, or if your form had some fields that you wanted
    to check after submission but are not DB fields. Why would you use the
    entire POST array?

    --
    Thanks!
    -Shawn
    http://www.spidean.com

    --
    PHP General Mailing List (http://www.php.net/)
    To unsubscribe, visit: http://www.php.net/unsub.php

    RE: Custom function for inserting values into MySQL

    am 05.11.2009 02:15:20 von Daevid Vincent

    > -----Original Message-----
    > From: Shawn McKenzie [mailto:nospam@mckenzies.net]
    > Sent: Wednesday, November 04, 2009 4:59 PM
    > To: Daevid Vincent
    > Cc: 'Allen McCabe'; 'PHP General'
    > Subject: Re: [PHP] Custom function for inserting values into MySQL
    >
    > Daevid Vincent wrote:
    > >> -----Original Message-----
    > >> From: Shawn McKenzie [mailto:nospam@mckenzies.net]
    > >> Sent: Wednesday, November 04, 2009 6:20 AM
    > >> To: Allen McCabe; PHP General
    > >> Subject: Re: [PHP] Custom function for inserting values into MySQL
    > >>
    > >> In your example, I would name my form inputs similar to name
    > >> ="data[user_id]".
    > >>
    > >> Then you just pass the $_POST['data'] array to your function.
    > >>
    > >> -Shawn
    > >>
    > >> Allen McCabe wrote:
    > >>> You raise some good points. I always name my input fields
    > after the
    > >>> entity names ( eg. input type="hidden" name ="user_id"
    > value=" ?php
    > >>> echo $resultRow['user_id'] ? " ).
    > >>>
    > >>> I suppose I am still in the phase of learning efficiency,
    > >> and perhaps
    > >>> trying to 'get out it' by writing functions that I can
    > just call and
    > >>> pass parameters instead of fully learning the core concepts.
    > >>>
    > >>> I just think functions are so damn cool :)
    > >>>
    > >>>
    > >>> I'll echo what the others have said about the
    > >> parameters. For me
    > >>> personally, if I am passing more than three parameters
    > >> (sometimes even
    > >>> three) I rethink my function. I'm not sure what you envision
    > >>> using this
    > >>> function for, but the approach I use for forms and
    > >> databases is always
    > >>> arrays. I get an array from my forms, I insert that
    > >> array into the
    > >>> database, and of course I fetch arrays out of the
    > >> database. These are
    > >>> all indexed the same with the index as the field name
    > >> of the table so
    > >>> it's easy.
    > >>>
    > >>>
    > >>> --
    > >>> Thanks!
    > >>> -Shawn
    > >>> http://www.spidean.com
    > >>>
    > >>>
    > >>>
    > >
    > > There are pro's and cons to this type of thing. In general
    > that is how I do
    > > it too, but you have to be aware of security and
    > organization. It's not
    > > always smart to expose your DB field names directly so you
    > might want to
    > > obscure them for some critical values. If your passing from
    > one controlled
    > > function/method to another then this isnt an issue so much.
    > >
    > > I also follow the ruby/rails ideal where tables are plural
    > names ("users")
    > > and classes are singular names ("user.class.php"). Tables
    > always have fields
    > > for 'id','created_on','timestamp','enabled'. Except in
    > 'glue table' cases
    > > (1:n or n:m). Classes extend a base class which handles a
    > lot of the minutea
    > > including the magic __get() and __set() routines as well as
    > knowing what
    > > table they should be through introspection (ie. Their own
    > file name).
    > >
    > > No need to name your fields as arrays. $_POST is already an
    > array. You've
    > > just added more complexity/dimensions. When you submit your
    > form just pass
    > > $_POST to your function instead. In the function, is where
    > you should do any
    > > normalizing, scrubbing and unsetting (as per good MVC ideology)...
    > >
    >
    > The way I normally do it I learned from the CakePHP framework which is
    > very similar to (I think an attempt at a clone of) Rails.
    > I'm not sure
    > if they do it the same way in Rails, but as you were mentioning, in a
    > Cake view of a form they use the table name as the array name
    > (name="Users[username]"). Internally to the framework this may make
    > things easier, but imagine you have a page with 2 or more forms that
    > update different tables, or if your form had some fields that
    > you wanted to check after submission but are not DB fields.

    The $_POST array will ONLY contain the key/values for the FORM that
    contained the submit button.












    So if you click the 'Add' button, you get back:
    $_POST['foo'] => 'bar', $_POST['action'] => 'Add'

    if you click the 'Update' button, you get back:
    $_POST['bee'] => 'boo', $_POST['action'] => 'Update'

    where's the confusion? You can only submit one form on a page at a time.

    > Why would you use the entire POST array?

    Presumably, anything in the form is of some value to your database and you'd
    want it. Otherwise why is it in the form?


    --
    PHP General Mailing List (http://www.php.net/)
    To unsubscribe, visit: http://www.php.net/unsub.php

    Re: Custom function for inserting values into MySQL

    am 05.11.2009 15:13:50 von Shawn McKenzie

    Daevid Vincent wrote:
    >
    >
    >> -----Original Message-----
    >> From: Shawn McKenzie [mailto:nospam@mckenzies.net]
    >> Sent: Wednesday, November 04, 2009 4:59 PM
    >> To: Daevid Vincent
    >> Cc: 'Allen McCabe'; 'PHP General'
    >> Subject: Re: [PHP] Custom function for inserting values into MySQL
    >>
    >> Daevid Vincent wrote:
    >>>> -----Original Message-----
    >>>> From: Shawn McKenzie [mailto:nospam@mckenzies.net]
    >>>> Sent: Wednesday, November 04, 2009 6:20 AM
    >>>> To: Allen McCabe; PHP General
    >>>> Subject: Re: [PHP] Custom function for inserting values into MySQL
    >>>>
    >>>> In your example, I would name my form inputs similar to name
    >>>> ="data[user_id]".
    >>>>
    >>>> Then you just pass the $_POST['data'] array to your function.
    >>>>
    >>>> -Shawn
    >>>>
    >>>> Allen McCabe wrote:
    >>>>> You raise some good points. I always name my input fields
    >> after the
    >>>>> entity names ( eg. input type="hidden" name ="user_id"
    >> value=" ?php
    >>>>> echo $resultRow['user_id'] ? " ).
    >>>>>
    >>>>> I suppose I am still in the phase of learning efficiency,
    >>>> and perhaps
    >>>>> trying to 'get out it' by writing functions that I can
    >> just call and
    >>>>> pass parameters instead of fully learning the core concepts.
    >>>>>
    >>>>> I just think functions are so damn cool :)
    >>>>>
    >>>>>
    >>>>> I'll echo what the others have said about the
    >>>> parameters. For me
    >>>>> personally, if I am passing more than three parameters
    >>>> (sometimes even
    >>>>> three) I rethink my function. I'm not sure what you envision
    >>>>> using this
    >>>>> function for, but the approach I use for forms and
    >>>> databases is always
    >>>>> arrays. I get an array from my forms, I insert that
    >>>> array into the
    >>>>> database, and of course I fetch arrays out of the
    >>>> database. These are
    >>>>> all indexed the same with the index as the field name
    >>>> of the table so
    >>>>> it's easy.
    >>>>>
    >>>>>
    >>>>> --
    >>>>> Thanks!
    >>>>> -Shawn
    >>>>> http://www.spidean.com
    >>>>>
    >>>>>
    >>>>>
    >>> There are pro's and cons to this type of thing. In general
    >> that is how I do
    >>> it too, but you have to be aware of security and
    >> organization. It's not
    >>> always smart to expose your DB field names directly so you
    >> might want to
    >>> obscure them for some critical values. If your passing from
    >> one controlled
    >>> function/method to another then this isnt an issue so much.
    >>>
    >>> I also follow the ruby/rails ideal where tables are plural
    >> names ("users")
    >>> and classes are singular names ("user.class.php"). Tables
    >> always have fields
    >>> for 'id','created_on','timestamp','enabled'. Except in
    >> 'glue table' cases
    >>> (1:n or n:m). Classes extend a base class which handles a
    >> lot of the minutea
    >>> including the magic __get() and __set() routines as well as
    >> knowing what
    >>> table they should be through introspection (ie. Their own
    >> file name).
    >>> No need to name your fields as arrays. $_POST is already an
    >> array. You've
    >>> just added more complexity/dimensions. When you submit your
    >> form just pass
    >>> $_POST to your function instead. In the function, is where
    >> you should do any
    >>> normalizing, scrubbing and unsetting (as per good MVC ideology)...
    >>>
    >> The way I normally do it I learned from the CakePHP framework which is
    >> very similar to (I think an attempt at a clone of) Rails.
    >> I'm not sure
    >> if they do it the same way in Rails, but as you were mentioning, in a
    >> Cake view of a form they use the table name as the array name
    >> (name="Users[username]"). Internally to the framework this may make
    >> things easier, but imagine you have a page with 2 or more forms that
    >> update different tables, or if your form had some fields that
    >> you wanted to check after submission but are not DB fields.
    >
    > The $_POST array will ONLY contain the key/values for the FORM that
    > contained the submit button.
    >
    >


    >
    >
    >

    >
    >
    >

    >
    >
    >

    >
    > So if you click the 'Add' button, you get back:
    > $_POST['foo'] => 'bar', $_POST['action'] => 'Add'
    >
    > if you click the 'Update' button, you get back:
    > $_POST['bee'] => 'boo', $_POST['action'] => 'Update'
    >
    > where's the confusion? You can only submit one form on a page at a time.
    >
    >> Why would you use the entire POST array?
    >
    > Presumably, anything in the form is of some value to your database and you'd
    > want it. Otherwise why is it in the form?
    >

    I guess I was going for multiple tables and not multiple forms. Consider
    a form that takes input for a Users table and a Groups table. As for the
    inputs not needed by the DB, there are too many examples I could give
    with lots of inputs, but here is the simplest example I can think of:

    username
    password
    captcha
    rememberme

    Presumably you don't need the captcha or rememberme in the DB. To each
    his own.

    --
    Thanks!
    -Shawn
    http://www.spidean.com

    --
    PHP General Mailing List (http://www.php.net/)
    To unsubscribe, visit: http://www.php.net/unsub.php

    RE: Custom function for inserting values into MySQL

    am 05.11.2009 22:07:46 von Daevid Vincent

    > -----Original Message-----
    > From: Shawn McKenzie [mailto:nospam@mckenzies.net]
    > Sent: Thursday, November 05, 2009 6:14 AM
    > To: Daevid Vincent
    > Cc: 'Allen McCabe'; 'PHP General'
    > Subject: Re: [PHP] Custom function for inserting values into MySQL
    >
    > Daevid Vincent wrote:
    > >
    > >
    > >> -----Original Message-----
    > >> From: Shawn McKenzie [mailto:nospam@mckenzies.net]
    > >> Sent: Wednesday, November 04, 2009 4:59 PM
    > >> To: Daevid Vincent
    > >> Cc: 'Allen McCabe'; 'PHP General'
    > >> Subject: Re: [PHP] Custom function for inserting values into MySQL
    > >>
    > >> Daevid Vincent wrote:
    > >>>> -----Original Message-----
    > >>>> From: Shawn McKenzie [mailto:nospam@mckenzies.net]
    > >>>> Sent: Wednesday, November 04, 2009 6:20 AM
    > >>>> To: Allen McCabe; PHP General
    > >>>> Subject: Re: [PHP] Custom function for inserting values
    > into MySQL
    > >>>>
    > >>>> In your example, I would name my form inputs similar to name
    > >>>> ="data[user_id]".
    > >>>>
    > >>>> Then you just pass the $_POST['data'] array to your function.
    > >>>>
    > >>>> -Shawn
    > >>>>
    > >>>> Allen McCabe wrote:
    > >>>>> You raise some good points. I always name my input fields
    > >> after the
    > >>>>> entity names ( eg. input type="hidden" name ="user_id"
    > >> value=" ?php
    > >>>>> echo $resultRow['user_id'] ? " ).
    > >>>>>
    > >>>>> I suppose I am still in the phase of learning efficiency,
    > >>>> and perhaps
    > >>>>> trying to 'get out it' by writing functions that I can
    > >> just call and
    > >>>>> pass parameters instead of fully learning the core concepts.
    > >>>>>
    > >>>>> I just think functions are so damn cool :)
    > >>>>>
    > >>>>>
    > >>>>> I'll echo what the others have said about the
    > >>>> parameters. For me
    > >>>>> personally, if I am passing more than three parameters
    > >>>> (sometimes even
    > >>>>> three) I rethink my function. I'm not sure what
    > you envision
    > >>>>> using this
    > >>>>> function for, but the approach I use for forms and
    > >>>> databases is always
    > >>>>> arrays. I get an array from my forms, I insert that
    > >>>> array into the
    > >>>>> database, and of course I fetch arrays out of the
    > >>>> database. These are
    > >>>>> all indexed the same with the index as the field name
    > >>>> of the table so
    > >>>>> it's easy.
    > >>>>>
    > >>>>>
    > >>>>> --
    > >>>>> Thanks!
    > >>>>> -Shawn
    > >>>>> http://www.spidean.com
    > >>>>>
    > >>>>>
    > >>>>>
    > >>> There are pro's and cons to this type of thing. In general
    > >> that is how I do
    > >>> it too, but you have to be aware of security and
    > >> organization. It's not
    > >>> always smart to expose your DB field names directly so you
    > >> might want to
    > >>> obscure them for some critical values. If your passing from
    > >> one controlled
    > >>> function/method to another then this isnt an issue so much.
    > >>>
    > >>> I also follow the ruby/rails ideal where tables are plural
    > >> names ("users")
    > >>> and classes are singular names ("user.class.php"). Tables
    > >> always have fields
    > >>> for 'id','created_on','timestamp','enabled'. Except in
    > >> 'glue table' cases
    > >>> (1:n or n:m). Classes extend a base class which handles a
    > >> lot of the minutea
    > >>> including the magic __get() and __set() routines as well as
    > >> knowing what
    > >>> table they should be through introspection (ie. Their own
    > >> file name).
    > >>> No need to name your fields as arrays. $_POST is already an
    > >> array. You've
    > >>> just added more complexity/dimensions. When you submit your
    > >> form just pass
    > >>> $_POST to your function instead. In the function, is where
    > >> you should do any
    > >>> normalizing, scrubbing and unsetting (as per good MVC ideology)...
    > >>>
    > >> The way I normally do it I learned from the CakePHP
    > framework which is
    > >> very similar to (I think an attempt at a clone of) Rails.
    > >> I'm not sure
    > >> if they do it the same way in Rails, but as you were
    > mentioning, in a
    > >> Cake view of a form they use the table name as the array name
    > >> (name="Users[username]"). Internally to the framework
    > this may make
    > >> things easier, but imagine you have a page with 2 or more
    > forms that
    > >> update different tables, or if your form had some fields that
    > >> you wanted to check after submission but are not DB fields.
    > >
    > > The $_POST array will ONLY contain the key/values for the FORM that
    > > contained the submit button.
    > >
    > >


    > >
    > >
    > >

    > >
    > >
    > >

    > >
    > >
    > >

    > >
    > > So if you click the 'Add' button, you get back:
    > > $_POST['foo'] => 'bar', $_POST['action'] => 'Add'
    > >
    > > if you click the 'Update' button, you get back:
    > > $_POST['bee'] => 'boo', $_POST['action'] => 'Update'
    > >
    > > where's the confusion? You can only submit one form on a
    > page at a time.
    > >
    > >> Why would you use the entire POST array?
    > >
    > > Presumably, anything in the form is of some value to your
    > database and you'd
    > > want it. Otherwise why is it in the form?
    > >
    >
    > I guess I was going for multiple tables and not multiple
    > forms. Consider a form that takes input for a Users table
    > and a Groups table. As for the inputs not needed by the DB,
    > there are too many examples I could give
    > with lots of inputs, but here is the simplest example I can think of:
    >
    > username
    > password
    > captcha
    > rememberme
    >
    > Presumably you don't need the captcha or rememberme in the
    > DB. To each his own.

    Right, so that (again) is why your CONTROLLER (MVC) does the scrubbing as
    previously illustrated:

    function process_data($data)
    {
    //perhaps you don't care about captcha and submit etc.
    unset($data['submit']);
    unset($data['captcha']);
    unset($data['rememberme']);
    ....


    If you really want 'groups' then I would suggest a prefix scheme so you can
    then weed out or work with the 'groups' you wanted...

    user_name
    user_email
    user_password
    user_captcha
    ....
    group_name
    group_id
    ....

    If you use JavaScript in your pages for pre-checking before submit, working
    with 'user[name]' is a little more cumbersome than just working with
    'user_name' IMHO. See this page for many examples of that headache:

    http://www.php.net/manual/en/faq.html.php#faq.html.arrays

    Like this is just UGLY: var foo = form['user[password]'].value;

    But as you say, to each their own. :)

    http://daevid.com


    --
    PHP General Mailing List (http://www.php.net/)
    To unsubscribe, visit: http://www.php.net/unsub.php